package com.example.wan1.base.activity;

import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.example.wan1.R;
import com.example.wan1.utils.ColorTheme;
import com.example.wan1.utils.ToolsUtils;
import com.example.wan1.widget.LoadingView;

import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/***
 * @Author: zxd
 * @CreateDate: 2020/6/16 11:28
 * @Description: 增加加载动画等
 * 因为加载的view是布局，不是弹窗，所以需要加入根布局，并且需要开启动画
 * 问题1：频繁的添加加载中的view及其移除 是否会对性能产生影响
 * 问题2：程序都已经退出了，toast还没有退出
 */
public abstract class RootActivity extends BaseMvpActivity {

    private LoadingView mLoadingView;

    private ViewGroup inflateView;
    private View errorView;
    //重复加载
    private TextView tvReload;

    private Context mContext;
    protected Unbinder mUnbinder;

    protected abstract @LayoutRes
    int initLayoutId();

    protected abstract void initData();

    protected abstract void initView();


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ColorTheme theme = new ColorTheme(this);
        theme.loadTheme();
        setContentView(initLayoutId());
        inflateView = findViewById(android.R.id.content);
        mContext = this;
        mUnbinder = ButterKnife.bind(this);
        mLoadingView = new LoadingView(this);

        initData();
        initView();
        //导航栏着色
        if (ToolsUtils.isOpenNavigationBar(this) && !ToolsUtils.getNightMode(this)) {
            Window window = getWindow();
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            // 状态栏（以上几行代码必须，参考setStatusBarColor|setNavigationBarColor方法源码）
            //window.setNavigationBarColor(Color.TRANSPARENT);
            if (ToolsUtils.getThemeColor(this) != 0)
                window.setNavigationBarColor(ToolsUtils.getThemeColor(this));
            else
                window.setNavigationBarColor(ToolsUtils.getAttrValue(this));
        }
    }

    public void showLoading() {
        showLoading("");
    }

    public void showLoading(String msg) {
        if (mLoadingView != null) {
            /*addLoading();*/
            inflateView.addView(mLoadingView);
            mLoadingView.setVisibility(View.VISIBLE);
            TextView shapeTv = mLoadingView.findViewById(R.id.shape_tv);
            shapeTv.setText(msg);
            mLoadingView.startFallAnimator();
        }
    }

    public void showLoading(int msgId) {
        if (mLoadingView != null) {
            /*addLoading();*/
            inflateView.addView(mLoadingView);
            mLoadingView.setVisibility(View.VISIBLE);
            TextView shapeTv = mLoadingView.findViewById(R.id.shape_tv);
            shapeTv.setText(msgId);
            mLoadingView.startFallAnimator();
        }
    }

    public void hideLoading() {
        if (mLoadingView != null) {
            mLoadingView.setVisibility(View.GONE);
            inflateView.removeView(mLoadingView);
        }
    }

    public void showError() {
        //如果错误，填充错误的布局
        //错误原因是布局的问题，布局中使用的是androidx之前的约束布局
        //https://www.jianshu.com/p/c931e33c5c4f

        //因为刚进来的时候有 加载中的动画，只能先移除，在进行错误的加载显示
        mLoadingView.setVisibility(View.GONE);
        inflateView.removeView(mLoadingView);

        LayoutInflater.from(this).inflate(R.layout.view_error, inflateView, true);
        errorView = inflateView.findViewById(R.id.view_error);
        tvReload = errorView.findViewById(R.id.tv_reload);
        tvReload.setOnClickListener(v -> reload());
    }

    /***
     * 重新加载
     * 相当于下拉刷新
     */
    public void reload() {
        //Log.i("zxd", "reload~~");
        errorView.setVisibility(View.GONE);
        inflateView.removeView(errorView);
    }

    @Override
    protected void onDestroy() {
        mUnbinder.unbind();
        super.onDestroy();
    }

    //下面这三个暂时没什么用，之前做添加了一次不重复加载的测试，这个等以后看下那个开源的框架后在做修改

    /***
     * 添加加载中
     */
    public void addLoading() {
        Log.i("zxd", "addLoading: " + getChildAt(inflateView));
        Log.i("zxd", "addLoading: " + inflateView.getChildCount());
        if (!getChildAt(inflateView)) {
            mLoadingView.setTag("1000");
            inflateView.addView(mLoadingView);
        }
    }

    //是否存在这个子viewA,返回true就是有，false就是没有
    private Boolean getChildAt(View view) {
        Boolean a = false;
        if (view instanceof ViewGroup) {
            ViewGroup vp = (ViewGroup) view;
            for (int i = 0; i < vp.getChildCount(); i++) {
                View viewchild = vp.getChildAt(i);
                //里面的1000即为需要找View的tag
                if (viewchild.getTag() != null && String.valueOf(viewchild.getTag()).equals("1000")) {
                    Log.i("zxd", String.valueOf(viewchild.getTag()));
                    return true;
                }
                a = a || getChildAt(viewchild);
            }
        }
        return a;
    }

    /***
     * 判断ViewGroup中是否存在这个tag的View
     * @param view
     * @param tag
     * @return
     */
    private Boolean getChildAt(View view, String tag) {
        Boolean a = false;
        if (view instanceof ViewGroup) {
            ViewGroup vp = (ViewGroup) view;
            for (int i = 0; i < vp.getChildCount(); i++) {
                View viewchild = vp.getChildAt(i);
                if (viewchild.getTag() != null && String.valueOf(viewchild.getTag()).equals(tag)) {
                    return true;
                }
                a = a || getChildAt(viewchild);
            }
        }
        return a;
    }

    /**
     * 设置 app 不随着系统字体的调整而变化
     */
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }
}
